#include "Functions/File.h"
#include "File/YamlLoader.h"
#include "Functions/String.h"
#include "Globals/Settings.h"
#include "TString.h"
#include "TSystem.h"
using namespace std;
using namespace BOSS_Afterburner::File;
using namespace BOSS_Afterburner::String;

/// This function creates a default output file name according to the `FrameworkSettings`. The file name consists of the plots output director, with the extension as subfolder and then the filename you want.
const char* BOSS_Afterburner::File::GetOutputFilename(const char* name, const char* ext)
{
  TString extension;
  if(ext)
    extension = ext;
  else
    extension = gExtension;
  return Form("%s/%s/%s.%s", gPlotOutputDir, YamlLoader::LastLoadedConfigName(), name,
              extension.Data());
}

/// This function creates a file name from the settings in `FrameworkSettings.h` and from the file name (without extension) that you feed it. You don't have to worry about creating the output directory, as it is created automatically from the slashes `/` in the resulting file name
const char* BOSS_Afterburner::File::SetOutputFilename(const char* name, const char* ext)
{
  // * Create full path * //
  const char* fullpath = GetOutputFilename(name, ext);
  // * Create dirname * //
  TString dirname(fullpath);
  Int_t   pos = dirname.Last('/');
  dirname.Resize(pos);
  gSystem->mkdir(dirname.Data(), true); // true: recursively create directory
  // * Get basename * //
  TString basename(fullpath);
  basename.Remove(0, pos + 1);
  // * Create file name and return * //
  return Form("%s/%s", dirname.Data(), basename.Data());
}

TString BOSS_Afterburner::File::BaseName(const TString& path)
{
  return gSystem->BaseName(path.Data());
}

TString BOSS_Afterburner::File::DirName(const TString& path)
{
  return gSystem->DirName(path.Data());
}

TString BOSS_Afterburner::File::GetAbsolutePath(const TString& path)
{
  TString output;
  TString currentPath = gSystem->pwd();
  if(gSystem->cd(path.Data())) output = gSystem->pwd();
  gSystem->cd(currentPath.Data());
  return output;
}